package com.qikux.filter;

import com.qikux.constraint.RssConst;
import org.haredot.web.RequestMappingHandler;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class AuthSessionFilter implements Filter {

    private List<String> needAuthUrls ;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String needAuthUrls = filterConfig.getInitParameter("needAuthUrls");
        String[] split = needAuthUrls.split(",");
        this.needAuthUrls = Arrays.stream(split).collect(Collectors.toList());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        if (needAuthUrls.contains(request.getServletPath())) {
            // 获取 session ， 并从 session 获取 对应的 登录 信息
            Object attribute = request.getSession().getAttribute(RssConst.CURRENT_USER);

            if (attribute == null) {
                // 说明 没有登录 ，让他跳转到登录页面
                response.sendRedirect(request.getContextPath() + "/login");
                return;
            }
        }
        // 如果 登录了， 则 继续向下执行
        chain.doFilter(request, response);

    }
}
